package com.gopay.bis.web.controller.wcpay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gopay.common.util.DateUtils;

/**
 * 接受微信推送过来的信息
 * @author dhj
 *
 */
@Controller
@Scope("prototype")
public class WxReceiverController {

	private Logger logger = LoggerFactory.getLogger(WxReceiverController.class);
	
	
	/**
     * 接受微信推送过来的信息，获取openId
     */
    @RequestMapping("/receiveOpenId")
    public String  receiveOpenId(HttpServletRequest request,HttpServletResponse response) {
		ServletInputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufReader = null;
		try {
			inputStream = request.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
			bufReader = new BufferedReader(inputStreamReader);
            StringBuffer xml = new StringBuffer();  
            String lineContent = "";  
            while ((lineContent = bufReader.readLine()) != null) {
            	xml.append(lineContent);
            }
	    	logger.info("-------微信推送过来的信息如下:{}-------",xml.toString());
	    	logger.info("-------微信推送时间:{}-------",DateUtils.getCurrDate(DateUtils.yyyy_MM_dd_HH_mm_ss));

			response.setStatus(HttpServletResponse.SC_OK);
			response.getWriter().write("");
			response.getWriter().flush();
		} catch (IOException e) {
			logger.error("-----接受微信推送事件错误----",e);
		} finally {
			try {
				if (null != inputStream) {
                    inputStream.close();
                }
				if (null != inputStreamReader) {
                    inputStreamReader.close();
                }
				if (null != bufReader) {
                    bufReader.close();
                }
			} catch (IOException e) {
				logger.error("关闭IO流异常： ", e);
			}
		}
		/*****************微信公众号URL配置验证******************/
    	
//    	String echostr=request.getParameter("echostr");
//    	String signature=request.getParameter("signature");
//    	logger.info("微信token验证，发送过来的echostr参数为:{},signature参数为:{}",echostr,signature);
//    	try {
//    		response.setStatus(HttpServletResponse.SC_OK);
//			response.getWriter().write(echostr);
//			response.getWriter().flush();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
        return null;
    }
}
